﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VOL.Entity.DomainModels;
using VOL.SmartMecial.Dtos;
using VOL.SmartMecial.Infrastructure;
using VOL.SmartMecial.IServices.PayInfoManage;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;

namespace VOL.SmartMecial.Services.PayInfoManage
{
       /// <summary>
       /// 确认缴费服务层类
       /// </summary>
    public class PayConfirmService : IPayConfirmService
    {
        private readonly IBaseRepository<Patient> _patientbaseRepository;
        private readonly IBaseRepository<PayInfo> _payinfobaseRepository;

        public PayConfirmService(IBaseRepository<Patient> patientbaseRepository, IBaseRepository<PayInfo> payinfobaseRepository)
        {
            _patientbaseRepository = patientbaseRepository;
            _payinfobaseRepository = payinfobaseRepository;
        }

        public async Task<List<PayconfirmDTO>> ShowPayConfirm()
        {
            var res = from a in _patientbaseRepository.GetAll()
                      join b in _payinfobaseRepository.GetAll() on a.PatientCode equals b.patientCode
                      select new PayconfirmDTO
                      {
                          PatientCode = a.PatientCode,
                          Name = a.Name,
                          Id = a.Id,
                          OfficeCode = a.OfficeCode,
                          RoomCode = b.RoomCode,
                          total = b.total,
                      };
            return await Task.FromResult(res.ToList());
        }
        
        /// <summary>
        /// 更新支付状态
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="payStatus">支付状态（1=已支付，0=未支付）</param>
        /// <returns>更新是否成功</returns>
        public async Task<int> UpdatePaymentStatus(string orderNo)
        {
            try
            {
                // 解析订单号，获取患者编号
                // 订单号格式可能是：PatientCode_timestamp
                string patientCode = orderNo;
                if (orderNo.Contains("_"))
                {
                   patientCode = orderNo.Split('_')[0];
                }
                
                // 查找对应的支付信息记录
                var payInfo = await _payinfobaseRepository.GetAll()
                    .FirstOrDefaultAsync(p => p.patientCode == orderNo);
                    
                if (payInfo == null)
                {
                    return 0;
                }

                // 更新支付状态
                payInfo.IsPay = 1;
                payInfo.PayTime = DateTime.Now;
                
                // 保存更改
                await _payinfobaseRepository.UpdateAsync(payInfo);
                return 1;
            }
            catch (Exception ex)
            {
                // 异常处理
                Console.WriteLine($"更新支付状态出错: {ex.Message}");
                return 2;
            }
        }
    }
}
